package com.sensePlusVR.main;

import android.annotation.SuppressLint;
import android.content.pm.ActivityInfo;
import android.graphics.SurfaceTexture;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;

import com.alibaba.fastjson.JSON;
import com.google.vr.cardboard.Real2DUiLayer;
import com.google.vr.cardboard.Real2DUiLayer.Real2DUiEvent;
import com.google.vr.cardboard.Real2DUiLayer.RealTipState;
import com.google.vr.cardboard.ThreadUtils;
import com.google.vr.cardboard.UiLayerExt;
import com.sensePlusVR.application.VRApplication;
import com.sensePlusVR.bean.BuriePointEventReqDto;
import com.sensePlusVR.bean.BuriedPointPlayData;
import com.sensePlusVR.setting.bluetooth.BluetoothPlayer.BTDataMsg;
import com.sensePlusVR.setting.bluetooth.BluetoothPlayer.BTEvent;
import com.sensePlusVR.utils.Constant;
import com.sensePlusVR.utils.ConstantURL;
import com.sensePlusVR.utils.DateTimeUtil;
import com.sensePlusVR.utils.MyLog;
import com.sensePlusVR.utils.MySharedPreferences;
import com.sensePlusVR.utils.PageJumpUtil;
import com.sensePlusVR.utils.UserUtil;
import com.senseplusvr.sdk.videoview.HemiGLView;
import com.senseplusvr.sdk.videoview.SvrConstant.UIImageTipAlignment;
import com.senseplusvr.sdk.videoview.SvrInterf;

import java.util.Timer;
import java.util.TimerTask;

@SuppressLint("InflateParams")
public class VrRealBaseActivity extends AppCompatActivity implements
		SvrInterf.SurfaceTexCallback {

	private static final String TAG = VrRealBaseActivity.class.getSimpleName();

	private String[] gameConfigs;

	private boolean mIsVrMode;
	
	private int gameId;

	private HemiGLView hemiGlView;

	private VRApplication vrApplication;

	private UiLayerExt uiLayer;

	private Real2DUiLayer real2DUiLayer;

	private GestureDetector tansGesDetector;

	private ScaleGestureDetector scaleGesDetector;

	private static final float RoateFactor = 0.05f;

	// 缩放半径
	private static final float scaleDepth = 30.0f;

	// 分级
	private static final float depDelta = 6.0f;

	private float spinX = 0.0f;

	private float spinY = 0.0f;

	private float zDepth = 0.0f;

	// 锁定视角
	private boolean trackingMode = false;

	private Timer mTimer;

	private TimerTask mTimerTask;

	private static final long timeDelay = 1000 * 3;

	private static final String gameTipVideo = "res/drawable-xxxhdpi-v4/device_video.png";

	private static final String gameTipCtrl = "res/drawable-xxxhdpi-v4/device_control.png";
	
	
	private boolean isShowGuesture = false;
	
	private LinearLayout guestureLayout;

	private BTEvent mBTEvent = new BTEvent() {

		@Override
		public void onConnected(boolean isConnected) {
			MyLog.d(TAG, "Bluetooth is connected : " + isConnected);
			if (isConnected) {

				vrApplication.setSensorEnable(true, mBTDataMsg);
			}
		}
	};

	@Override
	protected void onCreate(@Nullable Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		vrApplication = (VRApplication) getApplication();

		setContentView(R.layout.activity_real_game);

		hemiGlView = (HemiGLView) findViewById(R.id.hemiGlView);
		
		//测试
		hemiGlView.showFPS();
		
		//hemiGlView.setGyroDataEnable(false);

		hemiGlView.setSurfaceTexCallback(this);

		hemiGlView.setFocusable(true);

		hemiGlView.setFocusableInTouchMode(true);

		initDataFromIntent();
		
	    isFirstShowGesture();
	    
	    
	    startBuriedData();

	}
	
	
	private BuriePointEventReqDto buriePointEventReqDto;
	private long startTimeL = 0L;
	
	private void startBuriedData(){
	
		buriePointEventReqDto = new BuriePointEventReqDto();
		
		buriePointEventReqDto.setUid(UserUtil.getUserId());
		
		buriePointEventReqDto.setEvent(Constant.BURIED_GAME_PLAY);
		
		BuriedPointPlayData buriedPointPlayData = new BuriedPointPlayData();
		buriedPointPlayData.setGameId(gameId);
		buriedPointPlayData.setPlayMode(mIsVrMode == true?Constant.STR_VR:Constant.STR_2D);
		
		buriePointEventReqDto.setData(JSON.toJSONString(buriedPointPlayData));
		
		buriePointEventReqDto.setRemark(mIsVrMode == true?Constant.STR_VR:Constant.STR_2D);
		
		long timeL = System.currentTimeMillis();
		startTimeL = timeL;
		String timeStr = DateTimeUtil.toDateTimeString(timeL);
		buriePointEventReqDto.setEvent_time(timeStr);
		
		buriePointEventReqDto.setStart_time(timeL);
		
		buriePointEventReqDto.setMode(ConstantURL.BURIED_MODE);
		
		BuriePointEventReqDto.saveOrUpdate(buriePointEventReqDto);
		
	}
	
	private void endBuriedData(){
		
		long endTimeL = System.currentTimeMillis();
		long duration = endTimeL - startTimeL;
		
		buriePointEventReqDto.setDuration(duration);
		
		buriePointEventReqDto.setEnd_time(endTimeL);
		
		buriePointEventReqDto.setFlag(Constant.BURIED_FLAG_SUCCESS);
		
		BuriePointEventReqDto.saveOrUpdate(buriePointEventReqDto);
		
		
	}


	private void initDataFromIntent() {

		Bundle bundle = getIntent().getExtras();

		mIsVrMode = bundle.getBoolean(PageJumpUtil.VRMode_KEY, true);
		
		gameId = bundle.getInt(PageJumpUtil.GAME_ID_KEY);
		
		MyLog.d(TAG, "gameId : " + gameId);

		String gameParas = bundle.getString(PageJumpUtil.RealConfig_KEY);

		gameConfigs = gameParas.split(";");
		
		hemiGlView.setVrMode(mIsVrMode);

		if (mIsVrMode) {

			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

			uiLayer = new UiLayerExt(this);

			uiLayer.attachUiLayerToActivity(this);

			uiLayer.setAlignmentMarkerEnabled(mIsVrMode);

			uiLayer.setBackButtonListener(mIsVrMode ? backRunable : null);

		} else {

			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

			real2DUiLayer = new Real2DUiLayer(this);

			real2DUiLayer.setReal2DUiEvent(mReal2DUiEvent);

			real2DUiLayer.attachUiLayerToActivity(this);

			tansGesDetector = new GestureDetector(this, onTransGestureListener);

			scaleGesDetector = new ScaleGestureDetector(this,
					onScaleGestureListener);

			updateScale();

			mTimer = new Timer();

			showUI();

		}

	}
	
	/**
	 * 首次是否显示Guesture提示
	 */
	private void isFirstShowGesture() {
		isShowGuesture = MySharedPreferences.getBoolean2(this, MySharedPreferences.NAME_NOT_CLEAR, Constant.IS_FIRST_VIDEO_GESTURE);
	    if(!mIsVrMode && !isShowGuesture){
	     guestureLayout = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.gesture_guide,
	  				null, false);
	  		addContentView(guestureLayout,
	  				new android.widget.RelativeLayout.LayoutParams(-1,
	  						-1));
		    guestureLayout.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					if(!isShowGuesture){
						guestureLayout.setVisibility(View.GONE);
						isShowGuesture = true;
						MySharedPreferences.save2(VrRealBaseActivity.this, MySharedPreferences.NAME_NOT_CLEAR, Constant.IS_FIRST_VIDEO_GESTURE, isShowGuesture);
					}
				}
			});
	    }
	}

	/**
	 * 返回配置路径
	 * 
	 * @return
	 */
	public String[] getGameConfig() {

		return gameConfigs;
	}

	/**
	 * 是否vr模式
	 * 
	 * @return
	 */
	public boolean getVrMode() {

		return mIsVrMode;
	}

	/**
	 * 返回hemiGlView
	 * 
	 * @return
	 */
	public HemiGLView getHemiGlView() {

		return hemiGlView;
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();

		vrApplication.setSensorEnable(false, null);
		if(!isShowGuesture){
			isShowGuesture = true;
			MySharedPreferences.save2(VrRealBaseActivity.this, MySharedPreferences.NAME_NOT_CLEAR, Constant.IS_FIRST_VIDEO_GESTURE, isShowGuesture);
		}
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

		vrApplication.setBTEvent(mBTEvent);

		vrApplication.setSensorEnable(true, mBTDataMsg);
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		
		endBuriedData();
		
	}

	protected void onMaxKeyClick() {

	}

	protected void onMaxKeyLongPress() {

	}

	protected void onOptionKeyClick() {

	}

	// 锁定视角
	protected void onOptinKeyLongPress() {

		if (!mIsVrMode) {

			return;
		}

		if (trackingMode) {

			trackingMode = false;

			hemiGlView.pauseTracking();

		} else {

			trackingMode = true;

			hemiGlView.recenterTracking();
		}

	}

	protected void onKeyChanged(int code, int state) {
		if (code == Constant.BT_KEY_MAX) {

			if (state == Constant.BT_ACTION_ONE) {// 单击
				onMaxKeyClick();
			} else if (state == Constant.BT_ACTION_LONG) {// 长按
				onMaxKeyLongPress();
			}

		} else if (code == Constant.BT_KEY_O) {
			if (state == Constant.BT_ACTION_ONE) {// 单击
				onOptionKeyClick();
			} else if (state == Constant.BT_ACTION_LONG) {// 长按
				onOptinKeyLongPress();
			}
		}
	}

	protected void onDataReceived(float depth, float freq, float smoothFactor) {

	}

	private BTDataMsg mBTDataMsg = new BTDataMsg() {

		@Override
		public void onKeyStateChanged(int code, int state) {

			onKeyChanged(code, state);
		}

		@Override
		public void onDataReceive(float depth, float freq, float smoothFactor) {

			onDataReceived(depth, freq, smoothFactor);

		}
	};

	@Override
	public void onSurfaceTexture(SurfaceTexture surfacetexture) {


	}

	private Runnable backRunable = new Runnable() {

		@Override
		public void run() {

			onBackPressed();

		}
	};

	// 2DUi 回调用
	private Real2DUiEvent mReal2DUiEvent = new Real2DUiEvent() {

		@Override
		public void onEvent(int uiEvent) {

			MyLog.d(TAG, "Real2DUiEvent onEvent:" + uiEvent);

			switch (uiEvent) {
			case Real2DUiLayer.Real2DUiEvent_Back:

				onBackPressed();

				break;
			case Real2DUiLayer.Real2DUiEvent_Add:
				zDepth += depDelta;
				if (zDepth >= scaleDepth) {
					zDepth = scaleDepth;
				}
				hemiGlView.setHeadTrans(zDepth);

				updateScale();

				break;
			case Real2DUiLayer.Real2DUiEvent_Sub:

				zDepth -= depDelta;
				if (zDepth <= -scaleDepth) {
					zDepth = -scaleDepth;
				}
				hemiGlView.setHeadTrans(zDepth);

				updateScale();

				break;
			case Real2DUiLayer.Real2DUiEvent_Reset:
				spinX = 0.0f;
				spinY = 0.0f;
				zDepth = 0.0f;
				hemiGlView.setHeadRotate(spinX, spinY);
				hemiGlView.setHeadTrans(zDepth);
				updateScale();

				break;
			case Real2DUiLayer.Real2DUiEvent_Switch:
				onMaxKeyClick();

				break;
			case Real2DUiLayer.Real2DUiEvent_Max:

				onMaxKeyLongPress();

				break;

			case Real2DUiLayer.Real2DUiEvent_Tip:
				MyLog.d(TAG, "Real2DUiEvent_Tip is click...");

				// TODO 视频游戏切换
				onOptionKeyClick();

				break;

			case Real2DUiLayer.Real2DUiEvent_All:

				showUI();

				break;

			default:
				break;
			}
		}

		@Override
		public void onMove(int uiAction) {

			Log.d(TAG, "onMove uiAction : " + uiAction);
			// 当开始移动让UI始终显示，避免showUI多次频繁执行
			if (uiAction == Real2DUiLayer.Real2DUiAction_MoveStart) {

				showUIVisible(true);

			} else if (uiAction == Real2DUiLayer.Real2DUiAction_MoveEnd) {

				showUI();

			}

		}
	};

	@Override
	public boolean dispatchTouchEvent(MotionEvent event) {

		super.dispatchTouchEvent(event);
		// 如果leftUI移动则视频移动和缩放事件失效
		if (!(!mIsVrMode && real2DUiLayer.can2DUIMove())) {
			if (tansGesDetector != null) {
				tansGesDetector.onTouchEvent(event);
			}
			if (scaleGesDetector != null)
				scaleGesDetector.onTouchEvent(event);
		}
		return false;
	}

	/**
	 * 显示2dui
	 */
	private void showUI() {

		real2DUiLayer.setLeftUiVisible(true);

		if (mTimerTask != null) {

			mTimerTask.cancel();

			mTimerTask = null;

		}

		mTimerTask = new TimerTask() {

			@Override
			public void run() {

				real2DUiLayer.setLeftUiVisible(false);

				MyLog.d(TAG, "lefui hide");

			}
		};

		mTimer.schedule(mTimerTask, timeDelay);
	}

	private void showUIVisible(boolean isVisible) {

		if (mTimerTask != null) {

			mTimerTask.cancel();

			mTimerTask = null;

		}

		real2DUiLayer.setLeftUiVisible(isVisible);

	}

	private GestureDetector.OnGestureListener onTransGestureListener = new GestureDetector.SimpleOnGestureListener() {

		@Override
		public boolean onScroll(MotionEvent e1, MotionEvent e2,
				float distanceX, float distanceY) {

			spinY += distanceX * RoateFactor;

			spinX += distanceY * RoateFactor;

			hemiGlView.setHeadRotate(spinX, spinY);

			return false;
		}
	};

	private ScaleGestureDetector.OnScaleGestureListener onScaleGestureListener = new ScaleGestureDetector.SimpleOnScaleGestureListener() {

		@Override
		public boolean onScale(ScaleGestureDetector detector) {

			zDepth += (detector.getScaleFactor() - 1.0f) * scaleDepth;

			if (zDepth >= scaleDepth) {
				zDepth = scaleDepth;
			}
			if (zDepth <= -scaleDepth) {
				zDepth = -scaleDepth;
			}

			hemiGlView.setHeadTrans(zDepth);

			updateScale();

			Log.e(TAG, "scale factor:" + detector.getScaleFactor() + " zDepth:"
					+ zDepth);
			return false;
		}
	};

	/**
	 * 更新缩放数值
	 */
	private void updateScale() {

		//final int ratio = (int) ((zDepth + scaleDepth) * 0.5f / scaleDepth * 100);

		ThreadUtils.runOnUiThread(new Runnable() {

			@Override
			public void run() {

				// real2DUiLayer.showProgress(ratio);

			}
		});

	}

	/**
	 * 切换提示
	 * 
	 * @param active
	 */
	protected void showInteractiveUI(boolean active) {
		showInteractiveUI(active, true, true);

	}

	/**
	 * 控制NextTip显示
	 * 
	 * @param visible
	 * @param alpha
	 */
	public void setNextTipVisible(boolean visible, float alpha) {

		if (!mIsVrMode) {
			real2DUiLayer.setNextTipVisible(visible, alpha);
		}

	}

	protected void showInteractiveUI(boolean active, boolean isCenter,
			boolean isAnimation) {

		if (mIsVrMode) {

			hemiGlView.setUIImageTip(active ? gameTipCtrl : gameTipVideo);

			hemiGlView
					.setUIImageAlignment(isCenter ? UIImageTipAlignment.Alignment_Center
							: UIImageTipAlignment.Alignment_Default);

		} else {
			real2DUiLayer.setRealTipState(
					active ? RealTipState.RealTipState_Control
							: RealTipState.RealTipState_Video, isAnimation);

		}

	}
}
